<template>
	<view class="t-login">
		<!-- 页面装饰图片 -->
		<image class="img-a" src="https://zhoukaiwen.com/img/loginImg/2.png"></image>
		<image class="img-b" src="https://zhoukaiwen.com/img/loginImg/3.png"></image>

		<!-- 标题 -->
		<view class="t-b">{{ title }}</view>
		<view class="t-b2">欢迎使用MQTT安全登录</view>

		<!-- 登录状态提示 -->
		<view class="mqtt-status">
			<view :class="['status-indicator', mqttConnected ? 'connected' : 'disconnected']"></view>
			<text>{{ mqttStatusText }}</text>
		</view>

		<form class="cl">
			<view class="t-a">
				<image class="image" src="https://zhoukaiwen.com/img/loginImg/user.png"></image>
				<view class="line"></view>
				<input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
			</view>
			<view class="t-a">
				<image class="image" src="https://zhoukaiwen.com/img/loginImg/pwd.png"></image>
				<view class="line"></view>
				<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
			</view>
			<view class="t-a" v-if="captchaEnabled">
				<image class="image" src="https://zhoukaiwen.com/img/loginImg/code.png"></image>
				<view class="line"></view>
				<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
				<view class="captcha-image-wrapper">
					<image class="captcha-image" :src="codeUrl" alt="验证码图片" @click="getCode" />
				</view>
			</view>

			<button @tap="handleLogin()" :disabled="!mqttConnected || loginLoading">
				<text v-if="loginLoading">登录中...</text>
				<text v-else>登 录</text>
			</button>
		</form>

		<view class="t-f"><text>————— 安全登录协议 —————</text></view>
		<view class="login-info">
			<text>使用MQTT协议进行安全认证</text>
			<text>连接状态: {{ mqttConnected ? '已连接' : '未连接' }}</text>
			<text>客户端ID: {{ clientId }}</text>
		</view>
	</view>
</template>

<script>
	import {
		getCodeImg
	} from '@/api/login'
	import mqttMixin from '@/utils/mixins/mqttMixin.js'

	export default {
		mixins: [mqttMixin],
		data() {
			return {
				codeUrl: "",
				captchaEnabled: true,
				loginForm: {
					username: "admin",
					password: "admin123",
					code: "",
					uuid: ''
				},
				title: 'MQTT安全登录',
				loginLoading: false,
				mqttStatusText: '正在连接MQTT服务器...',
				responseTimeout: null
			};
		},
		computed: {
			responseTopic() {
				return `system/login/response/${this.clientId}`
			}
		},
		onLoad() {
			this.mqttStatusText = '正在初始化MQTT连接...'
		},
		mounted() {
			// this.mqttInit()
			// this.$on('mqtt-connected', this.handleMqttConnected)
			// this.$on('mqtt-disconnected', this.handleMqttDisconnected)
			// this.$on('mqtt-message', this.handleMqttMessage)
			// this.$on('mqtt-error', this.handleMqttError)
		},
		beforeDestroy() {
			this.$off('mqtt-connected', this.handleMqttConnected)
			this.$off('mqtt-disconnected', this.handleMqttDisconnected)
			this.$off('mqtt-message', this.handleMqttMessage)
			this.$off('mqtt-error', this.handleMqttError)
			this.mqttDisconnect()
		},
		methods: {
			handleMqttConnected() {
				console.log('订阅登录响应主题:')
				this.mqttStatusText = 'MQTT已连接，可以登录'
				console.log('订阅登录响应主题:', this.responseTopic)
				this.mqttSubscribe(this.responseTopic)
			},

			handleMqttDisconnected() {
				this.mqttStatusText = 'MQTT连接已断开'
			},

			handleMqttError(error) {
				console.error('MQTT错误:', error)
				this.mqttStatusText = `MQTT错误: ${error.type}`
			},

			handleMqttMessage({
				shortTopic,
				payload
			}) {
				console.log(`收到消息 [${shortTopic}]:`, payload)

				if (shortTopic === this.responseTopic) {
					this.handleLoginResponse(payload)
				}
			},

			// 处理登录响应
			handleLoginResponse(payload) {
				clearTimeout(this.responseTimeout)

				if (payload.success) {
					this.$modal.msgSuccess(payload.message)
					this.$store.commit('SET_TOKEN', payload.token)
					this.loginSuccess()
				} else {
					this.$modal.msgError(payload.message || '登录失败')
					this.loginLoading = false
				}
			},

			// 登录方法
			handleLogin() {
				if (!this.mqttConnected) {
					this.$modal.msgError("MQTT未连接，请稍后再试")
					return
				}

				if (this.loginForm.username === "") {
					this.$modal.msgError("请输入您的账号")
				} else if (this.loginForm.password === "") {
					this.$modal.msgError("请输入您的密码")
				} else if (this.loginForm.code === "" && this.captchaEnabled) {
					this.$modal.msgError("请输入验证码")
				} else {
					this.loginLoading = true
					this.$modal.loading("正在通过MQTT登录...")
					this.mqttLogin()
				}
			},

			// MQTT登录
			mqttLogin() {
				// 准备登录数据
				const loginData = {
					username: this.loginForm.username,
					password: this.loginForm.password,
					clientId: this.clientId
				}

				if (this.captchaEnabled) {
					loginData.code = this.loginForm.code
					loginData.uuid = this.loginForm.uuid
				}

				// 发布登录请求
				this.mqttPublish('system/login/request', loginData)

				// 设置响应超时
				this.responseTimeout = setTimeout(() => {
					this.$modal.msgError("登录响应超时")
					this.loginLoading = false
					this.$modal.closeLoading()
				}, 10000)
			},

			// 获取图形验证码
			getCode() {
				getCodeImg().then(res => {
					this.loginForm.code = ""
					this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + res.img
						this.loginForm.uuid = res.uuid
					}
				})
			},

			// 登录成功后处理
			loginSuccess() {
				this.$modal.closeLoading()
				this.loginLoading = false

				// 设置用户信息
				this.$store.dispatch('GetInfo').then(() => {
					this.$tab.reLaunch('/pages/index')
				}).catch(err => {
					console.error('获取用户信息失败:', err)
				})
			}
		}
	};
</script>

<style>
	.t-login {
		width: 650rpx;
		margin: 0 auto;
		font-size: 28rpx;
		color: #000;
		position: relative;
		z-index: 1;
		padding-top: 100rpx;
	}

	.img-a {
		position: absolute;
		width: 100%;
		top: -150rpx;
		right: 0;
		z-index: -1;
		opacity: 0.8;
	}

	.img-b {
		position: absolute;
		width: 50%;
		bottom: 0;
		left: -50rpx;
		z-index: -1;
		opacity: 0.6;
	}

	.t-b {
		text-align: center;
		font-size: 46rpx;
		color: #5677fc;
		padding: 100rpx 0 30rpx 0;
		font-weight: bold;
		text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
	}

	.t-b2 {
		text-align: center;
		font-size: 32rpx;
		color: #3a3a3a;
		padding: 0rpx 0 70rpx 0rpx;
	}

	.t-login button {
		font-size: 32rpx;
		background: #5677fc;
		color: #fff;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 50rpx;
		box-shadow: 0 5px 7px 0 rgba(86, 119, 252, 0.2);
		margin-top: 40rpx;
	}

	.t-login button[disabled] {
		background: #a0b1f9;
	}

	.t-login .input {
		padding: 0 20rpx 0 120rpx;
		height: 90rpx;
		line-height: 90rpx;
		margin-bottom: 40rpx;
		background: #f8f9ff;
		border: 1px solid #e6e9fa;
		font-size: 28rpx;
		border-radius: 50rpx;
		box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
	}

	.t-login .t-a {
		position: relative;
	}

	.t-login .t-a .image {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		left: 40rpx;
		top: 28rpx;
		z-index: 2;
	}

	.t-login .t-a .line {
		width: 2rpx;
		height: 40rpx;
		background-color: #dde2ff;
		position: absolute;
		top: 28rpx;
		left: 98rpx;
		z-index: 3;
	}

	.t-f {
		text-align: center;
		margin: 80rpx 0 30rpx 0;
		color: #666;
		position: relative;
	}

	.t-f text {
		background: #fff;
		padding: 0 20rpx;
		position: relative;
		z-index: 1;
		color: #5677fc;
		font-size: 26rpx;
	}

	.t-f::before {
		content: "";
		position: absolute;
		top: 50%;
		left: 0;
		right: 0;
		height: 1px;
		background: #e0e5ff;
		z-index: 0;
	}

	.login-info {
		background: #f0f4ff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-top: 30rpx;
		font-size: 24rpx;
		color: #5677fc;
		text-align: center;
		line-height: 1.8;
	}

	.mqtt-status {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		background: #f0f4ff;
		border-radius: 50rpx;
		padding: 10rpx 20rpx;
	}

	.status-indicator {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}

	.status-indicator.connected {
		background-color: #4caf50;
		box-shadow: 0 0 10rpx #4caf50;
	}

	.status-indicator.disconnected {
		background-color: #f44336;
	}

	.captcha-image-wrapper {
		position: absolute;
		right: 20rpx;
		top: 15rpx;
		width: 200rpx;
		height: 60rpx;
		border-radius: 10rpx;
		overflow: hidden;
		border: 1px solid #e0e5ff;
	}

	.captcha-image {
		width: 100%;
		height: 100%;
	}
</style>